package com.hardy.leetcode;

/**
 * 从单链表倒数第k个节点开始反转单链表 Created by 1340760685@qq.com on 2016/9/27.
 */
public class rotateList {
    public static class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public static ListNode rotateRight(ListNode head, int n) {
        if (head == null || head.next == null || n == 0) {
            return head;
        }
        ListNode newHead = new ListNode(-1);
        int len = 0;
        ListNode p = head;
        ListNode q = p;
        while (p != null) {
            len++;
            q = p;
            p = p.next;
        }
        n = n % len;
        if (n == 0) {
            return head;
        }
        p = head;
        for (int i = 1; i < len - n; i++) {
            p = p.next;
        }
        newHead.next = p.next;
        p.next = null;
        q.next = head;
        return newHead.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        ListNode res = rotateRight(head, 3);
        ListNode currNode = res;
        while (currNode != null) {
            System.out.print(currNode.val+" ");
            currNode = currNode.next;
        }
    }
}
